package middleware

import (
	"gitee.com/xinshortlink/internal/dto/resp"
	"gitee.com/xinshortlink/internal/dto/resp/bizerr"
	"gitee.com/xinshortlink/internal/pkg/token"
	"github.com/gin-gonic/gin"
)

const TokenKey = "xin-token"

// Auth 验证 token 是否有效
func Auth(util *token.LoginAccountUtil, t *token.Token, resp *resp.Util) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		accessToken := ctx.Request.Header.Get(TokenKey)
		if accessToken == "" {
			resp.Resp(ctx, bizerr.ErrTokenInvalid, nil)
			ctx.Abort()
			return
		}

		account, err := t.ParseToken(ctx, accessToken)
		if err != nil {
			resp.Resp(ctx, err, nil)
			ctx.Abort()
			return
		}

		if account == nil {
			resp.Resp(ctx, bizerr.ErrTokenInvalid, nil)
			ctx.Abort()
			return
		}

		c := util.SetUser(ctx.Request.Context(), account)

		ctx.Request = ctx.Request.WithContext(c)

		ctx.Next()
	}
}
